package com.xxmw.transaction.service.impl;

import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xxmw.transaction.service.HttpClient;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("httpClient")
public class HttpClientImpl implements HttpClient {
	
	@Autowired
	private CloseableHttpClient closeableHttpClient;

	@Override
	public String get(String url) {
		return get(url, null);
	}

	@Override
	public String get(String url, List<NameValuePair> params) {
		HttpGet httpGet = null;
		try {
			URIBuilder uriBuilder = new URIBuilder(url);
			uriBuilder.setParameters(params);
			httpGet = new HttpGet(uriBuilder.build());
		} catch (URISyntaxException e) {
			log.error("请求URL异常 url = " + url, e);
			return null;
		}
		return request(httpGet);
	}

	@Override
	public String post(String url, String body) {
		HttpPost post = new HttpPost(url);
		post.setHeader("Content-Type", "application/json;charset=UTF-8");
		StringEntity entity = new StringEntity(body, "UTF-8");
	    entity.setContentType("application/json");
	    post.setEntity(entity);
		return request(post);
	}
	
	@Override
	public String post(String url, List<NameValuePair> body) {
		HttpPost post = new HttpPost(url);
		HttpEntity httpEntity = new UrlEncodedFormEntity(body, Charset.forName("UTF-8"));
		post.setEntity(httpEntity);
		return request(post);
	}
	

	private String request(HttpUriRequest request) {
		String context = null;
		CloseableHttpResponse response = null;
		try {
			response  = closeableHttpClient.execute(request);
			HttpEntity entity = response.getEntity();
			context = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
		} catch (Exception e) {
			log.error("apache请求失败!", e);
		} finally {
			IOUtils.closeQuietly(response);
		}
		return context;
	}

	

	

}
